
const Koa = require('koa');
const bodyparser = require('koa-bodyparser')
const router = require('./routes');
const static_ = require('koa-static')
const path = require('path')
const { count } = require('./controller/count')
const { check_token } = require('./utils/token')
const app = new Koa();
//静态文件代理ha 
app.use(static_(
    path.join(__dirname, './public/')
))

app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  ctx.set('X-Response-Time', `${ms}ms`);
  // Access-Control-Allow-Credentials 设置为true会和 Access-Control-Allow-Origin":"*" 冲突的
  ctx.set("Access-Control-Allow-Credentials", false);
  // 这里获取 origin 请求头 而不是用 *
  ctx.set("Access-Control-Allow-Origin", "*");
  ctx.set("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,Authorization,token");
  ctx.set("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,HEADER");
  ctx.set("Content-Type", "application/json;charset=utf-8");
});
app.use(count)
app.use(check_token)
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
// logger

app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});

// response
app.use(router.routes(), router.allowedMethods())

app.listen(80);
console.log('oJBk','serve at localhost:'+2335)

